<?php
/**
 * Created by PhpStorm.
 * User: sunbo
 * Date: 2019/7/19
 * Time: 11:41 AM
 */

namespace app\index\controller;
include_once 'sdk_utils/Utils.php';
include_once 'sdk_utils/RsaEncrypt.php';
use think\Exception;
class CitPayApi extends CoinBaseContorller{


    private $api = null;
    function __construct() {
        parent::__construct();
        $this->api=new CitPay_Http_API();
    }
    //检查用户手机是否存在
   public function accountcheck($mobile) {
        $array = array(
            // 在citpay平台中获取
            "merchant_id" => $this->api->merchant_id,
            "mobile_num" => $mobile,
            "timestamp" => getMillisecond(),
        );
        $response= $this->api->http_request($array,'accountcheck');
        if($response["code"] != 200) {
            return false;
        }
        return true;
    }

    public function  accountRegister($mobile,$name){
        $array = array(
            // 在citpay平台中获取
            "merchant_id" => $this->api->merchant_id,
            "mobile_num" => $mobile,
            "customer_name" => $name,
            "timestamp" => getMillisecond(),
        );
        $response= $this->api->http_request($array,'accountRegister');
        if($response["code"] != 200) {
            exception($response["message"]);
        }
        return true;
    }

   //入金汇率
    public function realCurrencyRate($exchangeType) {
        $array = array(
            "merchant_id" => $this->api->merchant_id,
            "exchangeType"=> $exchangeType,
            "timestamp" => getMillisecond(),
        );
        $response= $this->api->http_request($array,'realCurrencyRate');
        return json_decode($response["response"]);
    }



    public  function depositOrder($amount,$legal,$sn,$mobile,$token,$redirectUrl) {
        $array = array(
            "merchant_id" => $this->api->merchant_id,
            "order_no" => $sn,
           "currency_type" => "USDT",
           "digital_amount" => $legal * pow(10,8),
           "customer_name" => $mobile,
           "legal_amount" => $amount,
            "redirectUrl"=>$redirectUrl,
            "customer_mobile" => $mobile,
           "notify_url" => $this->api->notify_url,
           "timestamp" => getMillisecond(),
            "token" => $token

        );
        $response= $this->api->http_request($array,'depositOrder');
        if($response["code"] != 200) {
            exception("citPay错误:".$response["message"]);
        }
        return $response;
    }

    //出金汇率
    public function realConvertCurrencyRate() {
        $array = array(
            "merchant_id" => $this->api->merchant_id,
            "legal_exchange_type" => "USDT2USD",
            "timestamp" => getMillisecond(),
        );
        $response= $this->api->http_request($array,'realConvertCurrencyRate');
        return json_decode($response["response"]);
    }
    //出金订单提交
    public  function outcomeOrder($amount,$usdt,$sn,$mobile,$legal_exchange_rate,$legal_exchange_type,$outcome_fee_rate,$token) {
        $array = array(
            "currency_type" => "USDT",
            "customer_mobile" => $mobile,
            "customer_name" => $mobile,
            "digital_amount" => $usdt * pow(10,8),
            "legal_amount" => $amount,
            "legal_exchange_rate"=>$legal_exchange_rate,
            "legal_exchange_type"=>$legal_exchange_type,
            "merchant_id" => $this->api->merchant_id,
            "notify_url" => $this->api->notify_url,
            "order_no" => $sn,
            "outcome_fee_rate" => $outcome_fee_rate,
            "token" => $token,
            "timestamp" => getMillisecond()
        );
        $response= $this->api->http_request($array,'outcomeOrder');
        if($response["code"] != 200) {
            exception($response["message"]);
        }
        $response["sn"]=$sn;
        return $response;
    }


    //提币
    public function withdrawCoin($mobile,$amount,$address) {
        $array = array(
            "customer_mobile" => $mobile,
            "merchant_id" => $this->api->merchant_id,
            "currency_type"=> "USDT",
            "address"=>$address,
            "legal_amount"=>$amount,
            "timestamp" => getMillisecond(),
        );
        $response= $this->api->http_request($array,'withdrawCoin');
        return $response;
    }

    //提币推送
    public function withdrawNotify($orderNo) {
        $array = array(
            "orderNo" => $orderNo,
            "merchantCode" => $this->api->merchant_id,
            "currencyType"=> "USDT",
            "token"=>"token"
        );
        $response= $this->api->http_request($array,'withdrawNotify');
        return json_decode($response["response"]);
    }

    //充值推送
    public  function  rechargeNotify($blockHeight,$address){
        $array = array(
            "blockHeight" => $blockHeight,
            "address" => $address,
            "timestamp" => getMillisecond(),
        );
        $response= $this->api->http_request($array,'rechargeNotify');
        $array= json_decode($response["response"]);
        uasort($array, function ($a, $b) {
            $sort = $a->height - $b->height;
            // 注释：如果两个元素比较结果相同，则它们在排序后的数组中的顺序未经定义。到 PHP 4.0.6 之前，用户自定义函数将保留这些元素的原有顺序。但是由于在 4.1.0 中引进了新的排序算法，结果将不是这样了，因为对此没有一个有效的解决方案。
            if ($sort == 0) return 0;
            // 返回1，将$a排在$b的后面
            return $sort > 0 ? 1 : -1;

        });
        return $array;
    }



    //获取充币地址
    public function getRechargeAddress($mobile) {
        $array = array(
            "mobile" => $mobile,
            "currencyType"=> "USDT",
            "timestamp" => getMillisecond(),
        );
        $response= $this->api->http_request($array,'getRechargeAddress');
        return json_decode($response["response"]);
    }


    //查找入金订单状态
    public function findOrder($order_no){
        $array = array(
            "order_no" => $order_no,
            "merchant_id"=> $this->api->merchant_id,
            "timestamp" => getMillisecond(),
        );
       // {"currencyType":"USDT","legalAmount":71.10000000,"legalType":"CNY","merchantCode":"0D6E4A0DFBB8797F","orderNo":"PlusToken4eef588bd3e5cfa2105671fbd4cae2cb","status":"已付","statusCode":"CC"}
        $response= $this->api->http_request($array,'findOrder');
        return json_decode($response["response"]);
    }

    //查找出金订单状态
    public function findOutcomeOrder($order_no){
        $array = array(
            "order_no" => $order_no,
            "merchant_id"=> $this->api->merchant_id,
            "timestamp" => getMillisecond(),
        );
        // {"currencyType":"USDT","legalAmount":71.10000000,"legalType":"CNY","merchantCode":"0D6E4A0DFBB8797F","orderNo":"PlusToken4eef588bd3e5cfa2105671fbd4cae2cb","status":"已付","statusCode":"CC"}
        $response= $this->api->http_request($array,'findOutcomeOrder');
        return json_decode($response["response"]);
    }



    /**
     *
     * @api {post} api/citpayapi/Cit_Pay_Register CitPay用户注册
     * @apiDescription  CitPay用户注册
     * @apiGroup citpay
     * @apiParam {string} mobile 手机号
     * @apiParam {string} countries_num 区号
     * @apiSuccess {string} data  空字符 成功
     * @apiVersion 1.0.1
     */
    public  function Cit_Pay_Register(){
        $mobile=$this->param("mobile");
        $countries_num=$this->param("countries_num");
        $userid=$this->getuserGuid();
        try{
            if($this->_Cit_Pay_Register($mobile,$countries_num,$userid)){
                return $this->json_data("","");
            }
            return $this->json_data("","注册失败");
        }catch (Exception $e){
            return $this->json_data("",$e->getMessage());
        }

    }

    public  function _Cit_Pay_Register($mobile,$countries_num,$userid){
        $new_mobile=$countries_num.','.$mobile;
        if($this->accountcheck($new_mobile)){
            exception("手机号已存在");
            return "";
        }
        if($this->accountRegister($new_mobile,$new_mobile)){
            $resutl=$this->db_exec(array("update token_sys_user set countries_num='".$countries_num."',citpay_phone='".$mobile."' where guid='".$userid."'"));
            if(strlen($resutl)>0){
                exception("更新用户失败");
            }
            return true;
        }
        return false;
    }


    /**
     *
     * @api {post} api/citpayapi/Cit_Pay_InsertOrder  CitPay入金
     * @apiDescription  CitPay入金
     * @apiGroup citpay
     * @apiParam {string} token_count 数量  不能是负数
     * @apiSuccess {string} url  跳转地址
     * @apiVersion 1.0.1
     */
    public  function Cit_Pay_InsertOrder(){
        $userid=$this->getuserGuid();
        $token_count=$this->param("token_count");
        try{
            $url= $this->_Cit_Pay_InsertOrder($token_count,$userid);
            return $this->json_data($url,"");
        }catch (Exception $e){
            return $this->json_data("",$e->getMessage());
        }
    }

    public function _Cit_Pay_InsertOrder($count,$userid){
        $row=$this->db_select("SELECT countries_num,citpay_phone from token_sys_user  where guid='".$userid."'");
        $mobile=$row[0]["citpay_phone"];
        $countries_num=$row[0]["countries_num"];
        $mobile=$countries_num.','.$mobile;

        $obj=$this->realCurrencyRate("USDT2CNY");
        $exchangeRate = $obj->exchangeRate;
        $token = $obj->token;
        $amount=number_format($count*$exchangeRate,2);

        $sn = str_replace('-','','PlusToken'.$this->uuid());

        //获取web回调地址
        $urlrow=$this->db_select("select value from token_sys_config where name='citpay_web_callback'");
        $url=$urlrow[0]["value"];
        $response = $this->depositOrder($amount,$count,$sn,$mobile,$token,$url);
        $obj =json_decode($response["response"]);

        //最后插入订单
        $execresult=$this->InsertCitBill($userid,$sn,$count*pow(10,8));
        if(strlen($execresult)>0){
            exception("插入交易订单出错");
        }
        return $obj->redirect_url;
    }

    function  InsertCitBill($userid,$sn,$count){
        return $this->db_exec(array("INSERT INTO token_bill_transaction_coin(guid,billdate,billdatetime,token_sys_user_guid,tokencount,token_sys_coin_guid,status,type,citpay_billno) 
VALUES(UUID(),now(),now(),'".$userid."',".$count.",'1',0,0,'".$sn."')"));
    }




    public function _Cit_Pay_outcomeOrder($count,$userid,$address,$sn){
        $row=$this->db_select("SELECT countries_num,citpay_phone from token_sys_user  where guid='".$userid."'");
        $mobile=$row[0]["citpay_phone"];
        $countries_num=$row[0]["countries_num"];
        $mobile=$countries_num.','.$mobile;
        $obj=$this->realConvertCurrencyRate();
        $legalExchangeType=$obj->legalExchangeType;
        $legalExchangeRate=$obj->legalExchangeRate;
        $outcomeFeeRate=$obj->outcomeFeeRate;
        $token=$obj->token;
        $currencyType=$obj->currencyType;
        $currencyAmount=$obj->currencyAmount;
        $amount=$count*$legalExchangeRate;
//        if($count*pow(10,8)>$currencyAmount){
//            exception("商户USDT余额不足");
//         return;
//        }
        $obj=$this->outcomeOrder($amount,$count,$sn,$mobile,$legalExchangeRate,$legalExchangeType,$outcomeFeeRate,$token);
        // 接下来就是提币接口
        $result=$this->withdrawCoin($mobile,$amount,$address);
        return $result;
    }


    //普通USDT 入金 查询 这个是定时任务
    public function Get_USDT_RechargeNotify(){
       $row=$this->db_select("select guid,token_sys_user_guid,address,begin_block_height,latest_block_height from token_user_coin_address a WHERE token_sys_coin_guid='1'");
        for ($i=0;$i<count($row);$i++){
            $height=$row[$i]["latest_block_height"]+1;
            $address=$row[$i]["address"];
            $userid=$row[$i]["token_sys_user_guid"];
            $guid=$row[$i]["guid"];
            $begin_block_height=$row[$i]["begin_block_height"];
            try{
                $result=$this->rechargeNotify($height,$address);
                if(count($result)==0){
                    continue;
                }
            }catch (Exception $e){
               $this->log("USDT 扫块出错：".$e->getMessage());
                continue;
            }
            $latest_block_height=$result[count($result)-1]->height;
            $array=array("update token_user_coin_address set latest_block_height=".$latest_block_height."  where guid='".$guid."'");
            //第一次使用则需要更新成区块高度
            if($begin_block_height==0){
                $begin_block_height=$result[0]->height;
                $array[]="update token_user_coin_address set begin_block_height=".$begin_block_height." where guid='".$guid."'";
            }

            for($n=0;$n<count($result);$n++){
                $uuid=$this->uuid();
                $array[]="insert into token_bill_transaction_coin(guid,billdate,billdatetime,token_sys_user_guid,sellout_address,fee,tokencount,token_sys_coin_guid,type,purchasein_address,transaction_id,status) VALUES
('".$uuid."','".date("Y-m-d")."','".date("Y-m-d H:i:s")."','".$userid."','".$result[$n]->sender."',0,".$result[$n]->amount*pow(10,8).",'1',0,'".$result[$n]->receiver."','".$result[$n]->txid."',1)";
            }
            $this->db_exec($array);
        }
    }



    public function Get_CitPay_BillState(){
        $row=$this->db_select("SELECT citpay_billno,token_sys_coin_guid from token_bill_transaction_coin where status=0 and type=0 and citpay_billno<>''");
        $this->Get_CitPay_BillState_ComeIn($row);

        $row=$this->db_select("SELECT citpay_billno,token_sys_coin_guid from token_bill_transaction_coin where status=2 and type=1 and citpay_billno<>''");
        $this->Get_CitPay_BillState_Sellout($row);
    }

    //获取所有提币单据状态
    public function Get_CitPay_BillState_Sellout($row){

        for ($i=0;$i<count($row);$i++){
            //"orderNo":"PlusToken4eef588bd3e5cfa2105671fbd4cae2cb","status":"已付","statusCode":"CC"
            $billno=$row[$i]["citpay_billno"];
            try{
                $result=$this->findOutcomeOrder($billno);
            }catch (Exception $e){
                $this->db_exec(array("update token_bill_transaction_coin set status=-1,message='".$e->getMessage()."' where citpay_billno='".$billno."'"));
                continue;
            }

            if($result==null){
                continue;
            }
            $status=0;
            switch ($result->statusCode){
                //成功
                case "CC":
                    $status=1;
                    break;
                //取消
                case "BB":
                    $status=-1;
                    break;
                default:
                    break;
            }
            if($status==0){
                continue;
            }
            $this->ReturnSellout($status,$billno);
        }
    }

    //提币订单退单  目前不退手续费
    public  function ReturnSellout($status,$billno){
        $row=$this->db_select("SELECT citpay_billno,token_sys_coin_guid,tokencount,token_sys_user_guid from token_bill_transaction_coin where citpay_billno='".$billno."'");
        $tokencount=$row[0]["tokencount"];
        $coinguid=$row[0]["token_sys_coin_guid"];
        $userid=$row[0]["token_sys_user_guid"];

        $array=array();
        $array[]="update token_bill_transaction_coin set status=".$status." where citpay_billno='".$billno."'";
        //如果取消了 需要退还手续费 以后再说
        if($status==-1){
            //如果是代币 退回代币数量
            if($this->IsCustomCoin($coinguid)){
                //扣交易费
                $array[]="update token_user_custom_coin_balance set token_count=token_count-".$tokencount." WHERE token_sys_user_guid='".$userid."'";
            }
        }
        $this->db_exec($array);
    }





    // 获取所有入金单据状态
    public function Get_CitPay_BillState_ComeIn($row){
        $array=array();
        for ($i=0;$i<count($row);$i++){
            //"orderNo":"PlusToken4eef588bd3e5cfa2105671fbd4cae2cb","status":"已付","statusCode":"CC"
            $billno=$row[$i]["citpay_billno"];
            try{
                $result=$this->findOrder($billno);
            }catch (Exception $e){
                $this->db_exec(array("update token_bill_transaction_coin set status=-1,message='".$e->getMessage()."' where citpay_billno='".$billno."'"));
                continue;
            }
            if($result==null){
                continue;
            }
            $status=0;
            switch ($result->statusCode){
                //成功
                case "CC":
                    $status=1;
                    break;
                //取消
                case "BB":
                    $status=-1;
                    break;
                //失败
                case "DD":
                    $status=-1;
                    break;
                default:
                    break;
            }
            if($status==0){
                continue;
            }
            $array[]="update token_bill_transaction_coin set status=".$status." where citpay_billno='".$billno."'";
            $this->db_exec($array);
        }
    }

}